﻿//-----------------------------------------------------------------------
// <copyright file="HashtableWebflowCatalog.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Routing;
    using Rosieks.Web.Flow.Metadata;

    public class HashtableWebflowCatalog : IWebflowCatalog, IEnumerable<KeyValuePair<string, WebflowModel>>
    {
        private readonly Hashtable webflowTable = new Hashtable();

        /// <summary>
        /// Initializes static members of the <see cref="T:HashtableWebflowCatalog"/> class.    
        /// </summary>
        static HashtableWebflowCatalog()
        {
            HashtableWebflowCatalog.Instance = new HashtableWebflowCatalog();
        }

        public static HashtableWebflowCatalog Instance
        {
            get;
            private set;
        }

        public WebflowModel Load(string name)
        {
            return this.webflowTable[name] as WebflowModel;
        }

        public void Register(WebflowModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (string.IsNullOrWhiteSpace(model.Name))
            {
                throw new ArgumentException("model");
            }

            this.webflowTable[model.Name] = model;

            model.RegisterRoutes(RouteTable.Routes);
        }

        public void Register(WebflowModel model, string alias)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (string.IsNullOrWhiteSpace(alias))
            {
                throw new ArgumentException("alias");
            }

            this.webflowTable[alias] = model;

            model.RegisterRoutes(RouteTable.Routes);
        }

        public void Unregister(string name)
        {
            this.webflowTable.Remove(name);
        }

        public IEnumerator<KeyValuePair<string, WebflowModel>> GetEnumerator()
        {
            return this.webflowTable.Cast<KeyValuePair<string, WebflowModel>>().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}
